package service4user

import (
	"Gin-Gorm-boke/boke_common/helper"
	models2 "Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/response"
	"Gin-Gorm-boke/boke_user/HttpCodeRegister"
	"github.com/gin-gonic/gin"
)

func GetUserInfo(c *gin.Context) {
	var user models2.User
	userId, exists := c.Get("userId")
	if !exists {
		response.RespnseLoginError(c)
		return
	}
	models2.Db.Model(new(models2.User)).Where("id=?", userId).Find(&user)
	response.ResponseOK(c, user)
	return

}

func UpdateUserInfo(c *gin.Context) {
	var user models2.User
	if err := c.ShouldBindJSON(&user); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	models2.Db.Model(new(models2.User)).Where("id=?", user.Id).Updates(&user)
	response.ResponseOK(c, nil)
	return

}

func Register(c *gin.Context) {
	var user models2.User
	if err := c.ShouldBindJSON(&user); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	if user.UserName == "" {
		c.JSON(HttpCodeRegister.USERNAME_NOT_NULL.Code, gin.H{
			"error": HttpCodeRegister.NICKNAME_NOT_NULL.Msg,
		})
		return
	}
	if user.Password == "" {
		c.JSON(HttpCodeRegister.PASSWORD_NOT_NULL.Code, gin.H{
			"error": HttpCodeRegister.PASSWORD_NOT_NULL.Msg,
		})
		return
	}
	if user.NickName == "" {
		c.JSON(HttpCodeRegister.NICKNAME_NOT_NULL.Code, gin.H{
			"error": HttpCodeRegister.NICKNAME_NOT_NULL.Msg,
		})
		return
	}
	if user.Email == "" {
		c.JSON(HttpCodeRegister.EMAIL_NOT_NULL.Code, gin.H{
			"error": HttpCodeRegister.EMAIL_NOT_NULL.Msg,
		})
	}
	var count int64
	models2.Db.Model(new(models2.User)).Where("user_name=?", user.UserName).Count(&count)
	if count > 0 {
		c.JSON(HttpCodeRegister.USERNAME_EXIST.Code, gin.H{
			"error": HttpCodeRegister.USERNAME_EXIST.Msg,
		})
		return
	}
	models2.Db.Model(new(models2.User)).Where("email=?", user.Email).Count(&count)
	if count > 0 {
		c.JSON(HttpCodeRegister.EMAIL_EXIST.Code, gin.H{
			"error": HttpCodeRegister.EMAIL_EXIST.Msg,
		})
		return
	}

	encodePassword, _ := helper.GetBcryptPassword(user.Password)
	user.Password = encodePassword
	models2.Db.Model(new(models2.User)).Create(&user)
	response.ResponseOK(c, nil)
	return

}
